package com.sunchangpeng.wechat.mp.url;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunchangpeng.wechat.core.WechatClient;
import com.sunchangpeng.wechat.mp.EndpointProvider;
import com.sunchangpeng.wechat.mp.MpAppSetting;
import com.sunchangpeng.wechat.mp.MpWechatClientFactory;

public class Shorturls {
    private WechatClient wechatClient;

    public void setWechatClient(WechatClient wechatClient) {
        this.wechatClient = wechatClient;
    }

    public static Shorturls with(MpAppSetting appSetting) {
        Shorturls shorturls = new Shorturls();
        shorturls.setWechatClient(MpWechatClientFactory.getInstance().with(appSetting));
        return shorturls;
    }

    /**
     * 长链接转换成短链接
     */
    public String url2short(String longUrl) {
        String url = EndpointProvider.get("url.url.toshort");
        String response = wechatClient.getTextWithToken(url, JSON.toJSONString(new JSONObject()
                .fluentPut("action", "long2short")
                .fluentPut("long_url", longUrl)));
        return JSON.parseObject(response).getString("short_url");
    }
}
